#!/usr/bin/env python3
"""
FastMCP Multi-Service Server
提供翻译、天气查询和黄金价格查询服务的 MCP 服务器
"""

import asyncio
import requests
from typing import Optional
from fastmcp import FastMCP

# 创建 MCP 应用实例
mcp = FastMCP("Multi-Service Server")

@mcp.tool()
def translate(msg: str, output_type: str = "json") -> dict | str:
    """
    翻译文本
    
    Args:
        msg: 要翻译的文本内容
        output_type: 输出格式，支持 "json" 或 "text"
    
    Returns:
        翻译结果，格式根据 output_type 参数决定
    """
    url = "https://api.lolimi.cn/API/qqfy/api.php"
    
    try:
        resp = requests.post(url, data={"msg": msg, "type": output_type}, timeout=10)
        resp.raise_for_status()
        
        if output_type == "json":
            try:
                return resp.json()
            except ValueError:
                return {"error": "Invalid JSON response", "raw_response": resp.text}
        else:
            return resp.text
            
    except requests.exceptions.RequestException as e:
        return {"error": f"Request failed: {str(e)}"}
    except Exception as e:
        return {"error": f"Unexpected error: {str(e)}"}

@mcp.tool()
def get_weather(city: str, output_type: str = "json") -> dict | str:
    """
    获取城市天气信息
    
    Args:
        city: 城市名称（支持中文城市名）
        output_type: 输出格式，支持 "json" 或 "text"
    
    Returns:
        天气信息，格式根据 output_type 参数决定
    """
    url = "https://api.lolimi.cn/API/weather/api.php"
    
    try:
        resp = requests.post(url, data={"city": city, "type": output_type}, timeout=10)
        resp.raise_for_status()
        
        if output_type == "json":
            try:
                return resp.json()
            except ValueError:
                return {"error": "Invalid JSON response", "raw_response": resp.text}
        else:
            return resp.text
            
    except requests.exceptions.RequestException as e:
        return {"error": f"Request failed: {str(e)}"}
    except Exception as e:
        return {"error": f"Unexpected error: {str(e)}"}

@mcp.tool()
def get_gold_price(output_type: str = "json") -> dict | str:
    """
    获取当前黄金价格信息
    
    Args:
        output_type: 输出格式，支持 "json" 或 "text"
    
    Returns:
        黄金价格信息，格式根据 output_type 参数决定
    """
    url = "https://api.lolimi.cn/API/huangj/api.php"
    
    try:
        resp = requests.post(url, data={"无": "123"}, timeout=10)
        resp.raise_for_status()
        
        if output_type == "json":
            try:
                return resp.json()
            except ValueError:
                return {"error": "Invalid JSON response", "raw_response": resp.text}
        else:
            return resp.text
            
    except requests.exceptions.RequestException as e:
        return {"error": f"Request failed: {str(e)}"}
    except Exception as e:
        return {"error": f"Unexpected error: {str(e)}"}

@mcp.tool()
def service_status() -> dict:
    """
    检查所有服务的状态
    
    Returns:
        各个服务的可用性状态
    """
    status = {
        "translation_service": "unknown",
        "weather_service": "unknown", 
        "gold_price_service": "unknown",
        "timestamp": None
    }
    
    import datetime
    status["timestamp"] = datetime.datetime.now().isoformat()
    
    # 测试翻译服务
    try:
        result = translate("hello", "json")
        status["translation_service"] = "available" if not isinstance(result, dict) or "error" not in result else "error"
    except:
        status["translation_service"] = "error"
    
    # 测试天气服务
    try:
        result = get_weather("北京", "json")
        status["weather_service"] = "available" if not isinstance(result, dict) or "error" not in result else "error"
    except:
        status["weather_service"] = "error"
    
    # 测试黄金价格服务
    try:
        result = get_gold_price("json")
        status["gold_price_service"] = "available" if not isinstance(result, dict) or "error" not in result else "error"
    except:
        status["gold_price_service"] = "error"
    
    return status

def main():
    """启动 MCP 服务器"""
    import sys
    
    print("=" * 50)
    print("FastMCP Multi-Service Server")
    print("=" * 50)
    print("提供以下服务:")
    print("- 文本翻译 (translate)")
    print("- 天气查询 (get_weather)")
    print("- 黄金价格查询 (get_gold_price)")
    print("- 服务状态检查 (service_status)")
    print("=" * 50)
    
    try:
        # 运行 MCP 服务器
        mcp.run()
    except KeyboardInterrupt:
        print("\n服务器已停止")
        sys.exit(0)
    except Exception as e:
        print(f"服务器启动失败: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main()